package com.gzz.orchid.common.webmvc.interceptor;

import com.gzz.orchid.common.core.util.CryptoUtil;
import com.gzz.orchid.common.core.util.IPUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * 冪等性
 * 用法：
 *
 * @author higmd
 * Idempotent(fields = {"orderId"},timeout = 10)
 * GetMapping("/test") public String test(@RequestParam("orderId") String orderId, String remark){}
 * ————————————————
 */
@Slf4j
public class IdempotentInterceptor implements HandlerInterceptor {

    @Lazy
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (handler.getClass().equals(HandlerMethod.class)) {
            try {
                Idempotent idempotent = ((HandlerMethod) handler).getMethodAnnotation(Idempotent.class);
                if (Objects.isNull(idempotent)) {
                    return true;
                }
                String idempotentKey = this.idempotentKey(idempotent, request);
                Boolean success = redisTemplate.opsForValue().setIfAbsent(idempotentKey, 1, idempotent.timeout(), TimeUnit.MILLISECONDS);
                if (Boolean.FALSE.equals(success)) {
                    render(response, "请勿重复请求");
                    return false;
                }
            } catch (ClassCastException e) {
                log.error("获取Idempotent 异常:: {}", e.getMessage());
                return true;
            }
        }
        return true;
    }

    private String idempotentKey(Idempotent idempotent, HttpServletRequest request) {
        String[] fields = idempotent.fields();
        // 确保字段顺序一致
        Arrays.sort(fields);
        StringBuilder content = new StringBuilder();
        // 使用分隔符防止字段拼接歧义
        String delimiter = "|";

        for (String field : fields) {
            String parameter = request.getParameter(field);
            String encodedValue = (parameter == null ? "" : parameter);
            content.append(encodedValue).append(delimiter);
        }

        // 添加客户端 IP 地址
        String clientIp = IPUtil.getIpAddress(request);
        content.append(clientIp);
        return CryptoUtil.sha256Encode(content.toString());
    }


    /**
     * 接口渲染
     */
    private void render(HttpServletResponse response, String message) throws Exception {
        response.setContentType("application/json;charset=UTF-8");
        OutputStream out = response.getOutputStream();
        out.write(message.getBytes(StandardCharsets.UTF_8));
        out.flush();
        out.close();
    }
}
